#!/bin/bash

# 配置文件路径
dst_config_pash=$(find /root -name dst_config)

# 读取配置文件函数
rcv() { sed -n "s/$1=\(.*\)/\1/p" "$dst_config_pash"; }

# 使用函数读取变量
steamcmd=$(rcv "steamcmd")                               # steamcmd安装路径
force_install_dir=$(rcv "force_install_dir")             # 饥荒服务器安装路径
persistent_storage_root=$(rcv "persistent_storage_root") # 默认 ~/.klei

# 构建文件路径并检查文件是否存在
steamclient_64_so="$(realpath "$steamcmd")/linux64/steamclient.so"
steamclient_32_so="$(realpath "$steamcmd")/linux32/steamclient.so"
if [ ! -f "$steamclient_64_so" ] ||
    [ ! -f "$steamclient_32_so" ]; then
    echo "steamclient.so文件缺失, 请确定配置项“steamcmd安装路径”正确。"
fi
if [ ! -d "$force_install_dir" ]; then
    echo "force_install_dir目录丢失, 请确定配置项“饥荒服务器安装路径”正确。"
fi
if [ ! -d "$persistent_storage_root" ]; then
    persistent_storage_root=/root/.klei
fi

#
echo "目录列表："
echo "$steamclient_64_so"
echo "$steamclient_32_so"
echo "$force_install_dir"
echo "$persistent_storage_root"

# 创建目录
mkdir -p "$(realpath "$force_install_dir")/mods"
mkdir -p "$(realpath "$force_install_dir")/bin/lib32"
mkdir -p "$(realpath "$force_install_dir")/bin64/lib64"
mkdir -p "$(realpath "$force_install_dir")/linux64"

# 重写dedicated_server_mods_setup
echo "Mod列表："
grep -r 'workshop-' --include=modoverrides.lua "$persistent_storage_root" |
    sed -n 's/.*workshop-\([0-9]*\).*/ServerModSetup(\"\1\")/p' |
    sort |
    uniq | tee "$(realpath "$force_install_dir")/mods/dedicated_server_mods_setup.lua"

# 移植库
cp "$steamclient_32_so" "$(realpath "$force_install_dir")/bin/lib32/steamclient.so"
cp "$steamclient_64_so" "$(realpath "$force_install_dir")/bin64/lib64/steamclient.so"
cp "$steamclient_32_so" "$(realpath "$force_install_dir")/steamclient.so"
cp "$steamclient_64_so" "$(realpath "$force_install_dir")/linux64/steamclient.so"
